<?php

namespace App\Events;

use App\Models\Reply;
use App\Models\Topic;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class ReplyChange
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Topic $topic, $last_reply_user_id)
    {
        // todo 品论数量的统计
        $count = app(Reply::class)->where('topic_id', $topic->id)->count();
        // $topic->reply_count = $count;
        // $topic->save();

        // todo 删除最后一条评论时，last_replay_user_id 的处理逻辑
        DB::table('topics')->where('id', $topic->id)->update([
            'reply_count' =>  $count,
            'last_reply_user_id' => $last_reply_user_id
        ]);
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}
